package com.bestdata.TD440.datasend;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @desc 通过过滤上位机过来的数据，在白名单范围内的数据发送给原始数据处理线程；黑名单的数据直接放到缓存中，通过过期时间
 * 定期清理。
 * 白名单：在bd_senssor数据表中的数据属于白名单
 * 黑名单：不再bd_sensor数据表中全部属于黑名单
 */
public class UDPServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {

private static final Logger logger = LoggerFactory.getLogger(UDPServerHandler.class);

    private int counts = 0 ;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg)
        throws Exception {
        if (null == msg){
            return;
        }

        final ByteBuf buf = msg.content();
        int readableBytes = buf.readableBytes();
        byte[] content = new byte[readableBytes];
        buf.readBytes(content);
        String clientMessage = new String(content,"UTF-8");

        try {
            System.out.println(clientMessage);

            ctx.writeAndFlush( "sss");

        } catch (Exception e){
            e.printStackTrace();
        } finally {
//            ReferenceCountUtil.release(msg); // (2)
        }
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        ctx.close();
        cause.printStackTrace();
    }
}